﻿using System;
using DevExpress.Web.ASPxGridView;
using DevExpress.Data;
using ExpressionEngine;

namespace ASPxGridViewExpressionSummary
{
    public class ExpressionASPxGridView : ASPxGridView
    {
        private class DelegateValueProvider : IValueProvider
        {
            public DelegateValueProvider(Func<string, object> accessor)
            {
                Accessor = accessor;
            }

            public Func<string, object> Accessor { get; private set; }

            public double GetValue(string fieldName)
            {
                return Convert.ToDouble(Accessor(fieldName));
            }
        }

        public ExpressionASPxGridView()
        {
            CustomSummaryCalculate += OnCustomSummaryCalculate;
        }

        private void OnCustomSummaryCalculate(object sender, CustomSummaryEventArgs e)
        {
            if (!DesignMode)
            {
                ExpressionSummary summary = e.Item as ExpressionSummary;

                if (summary != null)
                {
                    switch (e.SummaryProcess)
                    {
                        case CustomSummaryProcess.Start:
                            e.TotalValue = summary.Start();
                            break;
                        case CustomSummaryProcess.Calculate:
                            summary.RowChanged(e.TotalValue, new DelegateValueProvider(e.GetValue));
                            break;
                        case CustomSummaryProcess.Finalize:
                            e.TotalValue = summary.GetResult(e.TotalValue);
                            break;
                    }
                }
            }
        }
    }
}
